document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('notifications');
  
  // Variables
  let currentPage = 1;
  let pageSize = 10;
  let totalPages = 0;
  let currentType = 'all';
  let currentStatus = null;
  
  // Initialize page
  initPage();
  
  /**
   * Initialize page
   */
  function initPage() {
    // Load notifications
    loadNotifications(currentPage, pageSize, currentType, currentStatus);
    
    // Add event listeners
    addEventListeners();
  }
  
  /**
   * Add event listeners
   */
  function addEventListeners() {
    // Tab switching
    const tabs = document.querySelectorAll('.notification-tab');
    tabs.forEach(tab => {
      tab.addEventListener('click', function() {
        const type = this.getAttribute('data-type');
        
        // Update active tab
        tabs.forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        
        // Update current type
        currentType = type;
        currentPage = 1;
        
        // Reload notifications
        loadNotifications(currentPage, pageSize, currentType, currentStatus);
      });
    });
    
    // Read all button
    document.getElementById('read-all-btn').addEventListener('click', function() {
      markAllAsRead();
    });
    
    // Modal close button
    document.querySelector('.modal-close').addEventListener('click', function() {
      closeDetailModal();
    });
  }
  
  /**
   * Load notifications
   */
  function loadNotifications(page, size, type, status) {
    const notificationListElement = document.getElementById('notification-list');
    notificationListElement.innerHTML = `
      <div class="loader-container">
        <div class="loader"></div>
      </div>
    `;
    
    // Prepare params
    const params = {
      page: page,
      size: size
    };
    
    // Add type filter if not 'all'
    if (type !== 'all') {
      params.type = type;
    }
    
    // Add status filter if provided
    if (status !== null) {
      params.status = status;
    }
    
    // Call API
    ApiService.get('/api/notification/list', params)
      .then(response => {
        if (response.code === 0 && response.data) {
          const { total, list } = response.data;
          
          // Update total pages
          totalPages = Math.ceil(total / size);
          
          // Render notifications
          renderNotifications(list);
          
          // Render pagination
          renderPagination(page, totalPages);
        } else {
          notificationListElement.innerHTML = `
            <div class="notification-empty">
              <i class="fas fa-inbox"></i>
              <p>加载消息失败，请稍后再试</p>
            </div>
          `;
        }
      })
      .catch(error => {
        console.error('Error loading notifications:', error);
        notificationListElement.innerHTML = `
          <div class="notification-empty">
            <i class="fas fa-inbox"></i>
            <p>加载消息失败，请稍后再试</p>
          </div>
        `;
      });
  }
  
  /**
   * Render notifications
   */
  function renderNotifications(notifications) {
    const notificationListElement = document.getElementById('notification-list');
    
    if (notifications.length === 0) {
      notificationListElement.innerHTML = `
        <div class="notification-empty">
          <i class="fas fa-inbox"></i>
          <p>暂无消息</p>
        </div>
      `;
      return;
    }
    
    let html = '';
    
    notifications.forEach(notification => {
      const isUnread = notification.status === 0;
      const iconClass = getIconClass(notification.type);
      const badgeClass = getBadgeClass(notification.type);
      const typeText = getTypeText(notification.type);
      
      html += `
        <div class="notification-item ${isUnread ? 'unread' : ''}" data-id="${notification.id}">
          <div class="notification-status"></div>
          <div class="notification-icon ${iconClass}">
            <i class="${getIconName(notification.type)}"></i>
          </div>
          <div class="notification-content">
            <div class="notification-header">
              <div class="notification-title">${notification.title}</div>
              <div class="notification-time">${Utils.formatDate(notification.createTime)}</div>
            </div>
            <div class="notification-preview">${getPreviewText(notification.content)}</div>
            <div class="notification-badge ${badgeClass}">${typeText}</div>
          </div>
          <div class="notification-actions">
            ${isUnread ? 
              `<div class="notification-action mark-read" data-id="${notification.id}" title="标记为已读">
                <i class="far fa-envelope-open"></i>
               </div>` : 
              ''}
            <div class="notification-action delete" data-id="${notification.id}" title="删除">
              <i class="far fa-trash-alt"></i>
            </div>
          </div>
        </div>
      `;
    });
    
    notificationListElement.innerHTML = html;
    
    // Add event listeners
    addNotificationItemListeners();
  }
  
  /**
   * Add event listeners to notification items
   */
  function addNotificationItemListeners() {
    // Notification item click (view details)
    const notificationItems = document.querySelectorAll('.notification-item');
    notificationItems.forEach(item => {
      item.addEventListener('click', function(e) {
        // Don't trigger if clicking on action buttons
        if (e.target.closest('.notification-action')) {
          return;
        }
        
        const id = this.getAttribute('data-id');
        viewNotificationDetail(id);
      });
    });
    
    // Mark as read action
    const markReadButtons = document.querySelectorAll('.notification-action.mark-read');
    markReadButtons.forEach(button => {
      button.addEventListener('click', function(e) {
        e.stopPropagation();
        const id = this.getAttribute('data-id');
        markAsRead(id);
      });
    });
    
    // Delete action
    const deleteButtons = document.querySelectorAll('.notification-action.delete');
    deleteButtons.forEach(button => {
      button.addEventListener('click', function(e) {
        e.stopPropagation();
        const id = this.getAttribute('data-id');
        deleteNotification(id);
      });
    });
  }
  
  /**
   * Render pagination
   */
  function renderPagination(currentPage, totalPages) {
    const paginationElement = document.getElementById('pagination');
    
    if (totalPages <= 1) {
      paginationElement.innerHTML = '';
      return;
    }
    
    let html = '<div class="pagination">';
    
    // Previous button
    html += `
      <div class="pagination-item ${currentPage === 1 ? 'disabled' : ''}" data-page="${currentPage - 1}">
        <i class="fas fa-chevron-left"></i>
      </div>
    `;
    
    // Page numbers
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, startPage + 4);
    
    for (let i = startPage; i <= endPage; i++) {
      html += `
        <div class="pagination-item ${i === currentPage ? 'active' : ''}" data-page="${i}">
          ${i}
        </div>
      `;
    }
    
    // Next button
    html += `
      <div class="pagination-item ${currentPage === totalPages ? 'disabled' : ''}" data-page="${currentPage + 1}">
        <i class="fas fa-chevron-right"></i>
      </div>
    `;
    
    html += '</div>';
    paginationElement.innerHTML = html;
    
    // Add pagination click event
    const paginationItems = document.querySelectorAll('.pagination-item:not(.disabled)');
    paginationItems.forEach(item => {
      item.addEventListener('click', function() {
        const page = parseInt(this.getAttribute('data-page'));
        currentPage = page;
        loadNotifications(page, pageSize, currentType, currentStatus);
      });
    });
  }
  
  /**
   * View notification detail
   */
  function viewNotificationDetail(id) {
    // Call API to get notification detail
    ApiService.get(`/api/notification/${id}`)
      .then(response => {
        if (response.code === 0 && response.data) {
          const notification = response.data;
          
          // Update modal content
          document.getElementById('detail-title').textContent = notification.title;
          document.getElementById('detail-type').textContent = getTypeText(notification.type);
          document.getElementById('detail-time').textContent = Utils.formatDate(notification.createTime, true);
          document.getElementById('detail-content').textContent = notification.content;
          
          // Show modal
          document.getElementById('notification-detail-modal').classList.add('show');
          
          // Mark as read if unread
          if (notification.status === 0) {
            markAsRead(id, false);
          }
        } else {
          Toast.error('获取消息详情失败');
        }
      })
      .catch(error => {
        console.error('Error loading notification detail:', error);
        Toast.error('获取消息详情失败');
      });
  }
  
  /**
   * Close detail modal
   */
  function closeDetailModal() {
    document.getElementById('notification-detail-modal').classList.remove('show');
  }
  
  /**
   * Mark notification as read
   */
  function markAsRead(id, reload = true) {
    ApiService.put(`/api/notification/read/${id}`)
      .then(response => {
        if (response.code === 0) {
          if (reload) {
            // Reload notifications
            loadNotifications(currentPage, pageSize, currentType, currentStatus);
          } else {
            // Just update the UI
            const notificationItem = document.querySelector(`.notification-item[data-id="${id}"]`);
            if (notificationItem) {
              notificationItem.classList.remove('unread');
              const markReadBtn = notificationItem.querySelector('.notification-action.mark-read');
              if (markReadBtn) {
                markReadBtn.remove();
              }
            }
          }
          
          // Refresh unread count in top navbar
          topNavBar.refreshNotificationCount();
        } else {
          Toast.error('标记已读失败');
        }
      })
      .catch(error => {
        console.error('Error marking notification as read:', error);
        Toast.error('标记已读失败');
      });
  }
  
  /**
   * Mark all notifications as read
   */
  function markAllAsRead() {
    ApiService.put('/api/notification/read-all')
      .then(response => {
        if (response.code === 0) {
          // Show success message
          Toast.success('已全部标记为已读');
          
          // Reload notifications
          loadNotifications(currentPage, pageSize, currentType, currentStatus);
          
          // Refresh unread count in top navbar
          topNavBar.refreshNotificationCount();
        } else {
          Toast.error('操作失败');
        }
      })
      .catch(error => {
        console.error('Error marking all notifications as read:', error);
        Toast.error('操作失败');
      });
  }
  
  /**
   * Delete notification
   */
  function deleteNotification(id) {
    // Confirm delete
    if (!confirm('确定要删除此消息吗？')) {
      return;
    }
    
    ApiService.delete(`/api/notification/${id}`)
      .then(response => {
        if (response.code === 0) {
          // Show success message
          Toast.success('删除成功');
          
          // Reload notifications
          loadNotifications(currentPage, pageSize, currentType, currentStatus);
        } else {
          Toast.error('删除失败');
        }
      })
      .catch(error => {
        console.error('Error deleting notification:', error);
        Toast.error('删除失败');
      });
  }
  
  /**
   * Get icon class based on notification type
   */
  function getIconClass(type) {
    switch (parseInt(type)) {
      case 1: return 'system';
      case 2: return 'transaction';
      case 3: return 'activity';
      default: return 'system';
    }
  }
  
  /**
   * Get icon name based on notification type
   */
  function getIconName(type) {
    switch (parseInt(type)) {
      case 1: return 'fas fa-cog';
      case 2: return 'fas fa-exchange-alt';
      case 3: return 'fas fa-bullhorn';
      default: return 'fas fa-bell';
    }
  }
  
  /**
   * Get badge class based on notification type
   */
  function getBadgeClass(type) {
    switch (parseInt(type)) {
      case 1: return 'system';
      case 2: return 'transaction';
      case 3: return 'activity';
      default: return '';
    }
  }
  
  /**
   * Get type text based on notification type
   */
  function getTypeText(type) {
    switch (parseInt(type)) {
      case 1: return '系统消息';
      case 2: return '交易通知';
      case 3: return '活动消息';
      default: return '未知类型';
    }
  }
  
  /**
   * Get preview text from content
   */
  function getPreviewText(content) {
    if (!content) return '';
    
    // Limit to 100 characters
    if (content.length > 100) {
      return content.substring(0, 100) + '...';
    }
    
    return content;
  }
});
